<template>
  <div class="debug-panel">
    <h3>🔧 API 调试面板</h3>
    
    <div class="debug-section">
      <h4>环境信息</h4>
      <div class="info-grid">
        <div class="info-item">
          <strong>开发模式：</strong>{{ isDev ? '是' : '否' }}
        </div>
        <div class="info-item">
          <strong>API URL：</strong>{{ currentApiUrl }}
        </div>
        <div class="info-item">
          <strong>时间戳：</strong>{{ timestamp }}
        </div>
      </div>
    </div>

    <div class="debug-section">
      <h4>测试按钮</h4>
      <div class="button-group">
        <button @click="testDirectFetch" :disabled="loading" class="test-btn">
          直接请求测试
        </button>
        <button @click="testProxyFetch" :disabled="loading" class="test-btn">
          代理请求测试
        </button>
        <button @click="testCorsProxy" :disabled="loading" class="test-btn">
          CORS代理测试
        </button>
        <button @click="analyzeDataStructure" :disabled="loading" class="test-btn">
          分析数据结构
        </button>
        <button @click="clearLogs" class="clear-btn">
          清除日志
        </button>
      </div>
    </div>

    <div class="debug-section">
      <h4>请求日志</h4>
      <div class="logs-container">
        <div v-if="logs.length === 0" class="no-logs">
          暂无日志
        </div>
        <div 
          v-for="(log, index) in logs" 
          :key="index"
          :class="['log-item', log.type]"
        >
          <span class="log-time">{{ log.time }}</span>
          <span class="log-type">[{{ log.type.toUpperCase() }}]</span>
          <span class="log-message">{{ log.message }}</span>
          <pre v-if="log.data" class="log-data">{{ formatData(log.data) }}</pre>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'

interface LogEntry {
  time: string
  type: 'info' | 'error' | 'success' | 'warning'
  message: string
  data?: any
}

const loading = ref(false)
const logs = ref<LogEntry[]>([])
const timestamp = ref('')

const isDev = computed(() => import.meta.env.DEV)
const currentApiUrl = computed(() => {
  return isDev.value 
    ? '/api/jsondata/newAreaCodeV2024.json'
    : 'https://hongcat.oss-cn-chengdu.aliyuncs.com/jsondata/newAreaCodeV2024.json'
})

function addLog(type: LogEntry['type'], message: string, data?: any) {
  logs.value.unshift({
    time: new Date().toLocaleTimeString(),
    type,
    message,
    data
  })
  
  // 保持最多50条日志
  if (logs.value.length > 50) {
    logs.value = logs.value.slice(0, 50)
  }
}

function formatData(data: any): string {
  if (data === null || data === undefined) return 'null'
  
  try {
    return JSON.stringify(data, null, 2)
  } catch {
    return String(data)
  }
}

async function testDirectFetch() {
  loading.value = true
  addLog('info', '开始直接请求测试...')
  
  try {
    const response = await fetch('https://hongcat.oss-cn-chengdu.aliyuncs.com/jsondata/newAreaCodeV2024.json')
    addLog('info', `响应状态: ${response.status} ${response.statusText}`)
    
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`)
    }
    
    const data = await response.json()
    addLog('success', '直接请求成功', { 
      dataType: Array.isArray(data) ? 'array' : typeof data,
      length: Array.isArray(data) ? data.length : 'N/A',
      sample: Array.isArray(data) ? data.slice(0, 2) : data
    })
  } catch (error) {
    addLog('error', `直接请求失败: ${error instanceof Error ? error.message : String(error)}`)
  } finally {
    loading.value = false
  }
}

async function testProxyFetch() {
  loading.value = true
  addLog('info', '开始代理请求测试...')
  
  try {
    const response = await fetch('/api/jsondata/newAreaCodeV2024.json')
    addLog('info', `代理响应状态: ${response.status} ${response.statusText}`)
    
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`)
    }
    
    const data = await response.json()
    addLog('success', '代理请求成功', { 
      dataType: Array.isArray(data) ? 'array' : typeof data,
      length: Array.isArray(data) ? data.length : 'N/A',
      sample: Array.isArray(data) ? data.slice(0, 2) : data
    })
  } catch (error) {
    addLog('error', `代理请求失败: ${error instanceof Error ? error.message : String(error)}`)
  } finally {
    loading.value = false
  }
}

async function testCorsProxy() {
  loading.value = true
  addLog('info', '开始CORS代理测试...')
  
  try {
    const proxyUrl = 'https://api.allorigins.win/get?url='
    const targetUrl = encodeURIComponent('https://hongcat.oss-cn-chengdu.aliyuncs.com/jsondata/newAreaCodeV2024.json')
    
    const response = await fetch(proxyUrl + targetUrl)
    addLog('info', `CORS代理响应状态: ${response.status} ${response.statusText}`)
    
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`)
    }
    
    const proxyResult = await response.json()
    const data = JSON.parse(proxyResult.contents)
    
    addLog('success', 'CORS代理请求成功', { 
      dataType: Array.isArray(data) ? 'array' : typeof data,
      length: Array.isArray(data) ? data.length : 'N/A',
      sample: Array.isArray(data) ? data.slice(0, 2) : data
    })
  } catch (error) {
    addLog('error', `CORS代理请求失败: ${error instanceof Error ? error.message : String(error)}`)
  } finally {
    loading.value = false
  }
}

async function analyzeDataStructure() {
  loading.value = true
  addLog('info', '开始分析数据结构...')
  
  try {
    // 尝试代理请求
    const response = await fetch('/api/jsondata/newAreaCodeV2024.json')
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`)
    }
    
    const data = await response.json()
    
    // 分析数据结构
    const analysis = {
      dataType: Array.isArray(data) ? 'array' : typeof data,
      isArray: Array.isArray(data),
      length: Array.isArray(data) ? data.length : 'N/A',
      hasCodeField: data.code !== undefined,
      hasDataField: data.data !== undefined,
      hasMessageField: data.message !== undefined
    }
    
    if (Array.isArray(data) && data.length > 0) {
      const firstItem = data[0]
      analysis['firstItemFields'] = Object.keys(firstItem)
      analysis['firstItemSample'] = firstItem
      
      // 检查常见字段
      analysis['hasIdField'] = firstItem.id !== undefined
      analysis['hasNameField'] = firstItem.name !== undefined
      analysis['hasCodeFieldInItem'] = firstItem.code !== undefined
      analysis['hasValueField'] = firstItem.value !== undefined
      analysis['hasAreaCodeField'] = firstItem.areaCode !== undefined
      analysis['hasAreaNameField'] = firstItem.areaName !== undefined
      analysis['hasChildrenField'] = firstItem.children !== undefined
      analysis['hasLevelField'] = firstItem.level !== undefined
      analysis['hasPidField'] = firstItem.pid !== undefined
    } else if (data.data && Array.isArray(data.data) && data.data.length > 0) {
      const firstItem = data.data[0]
      analysis['dataArrayLength'] = data.data.length
      analysis['firstDataItemFields'] = Object.keys(firstItem)
      analysis['firstDataItemSample'] = firstItem
      
      // 检查常见字段
      analysis['hasIdField'] = firstItem.id !== undefined
      analysis['hasNameField'] = firstItem.name !== undefined
      analysis['hasCodeFieldInItem'] = firstItem.code !== undefined
      analysis['hasValueField'] = firstItem.value !== undefined
      analysis['hasAreaCodeField'] = firstItem.areaCode !== undefined
      analysis['hasAreaNameField'] = firstItem.areaName !== undefined
      analysis['hasChildrenField'] = firstItem.children !== undefined
      analysis['hasLevelField'] = firstItem.level !== undefined
      analysis['hasPidField'] = firstItem.pid !== undefined
    }
    
    addLog('success', '数据结构分析完成', analysis)
    
    // 提供修复建议
    const suggestions = []
    if (!analysis.hasIdField && !analysis.hasCodeFieldInItem && !analysis.hasValueField) {
      suggestions.push('缺少ID字段，可能需要使用code或value字段')
    }
    if (!analysis.hasNameField) {
      suggestions.push('缺少name字段，可能需要使用label或title字段')
    }
    
    if (suggestions.length > 0) {
      addLog('warning', '修复建议', suggestions)
    }
    
  } catch (error) {
    addLog('error', `数据结构分析失败: ${error instanceof Error ? error.message : String(error)}`)
  } finally {
    loading.value = false
  }
}

function clearLogs() {
  logs.value = []
  addLog('info', '日志已清除')
}

function updateTimestamp() {
  timestamp.value = new Date().toLocaleString()
}

onMounted(() => {
  updateTimestamp()
  setInterval(updateTimestamp, 1000)
  addLog('info', '调试面板已初始化')
})
</script>

<style scoped>
.debug-panel {
  background-color: #f8f9fa;
  border: 1px solid #dee2e6;
  border-radius: 8px;
  padding: 20px;
  margin: 20px 0;
  font-family: 'Courier New', monospace;
}

.debug-panel h3 {
  color: #495057;
  margin-bottom: 20px;
  font-size: 18px;
}

.debug-section {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e9ecef;
}

.debug-section:last-child {
  border-bottom: none;
}

.debug-section h4 {
  color: #6c757d;
  margin-bottom: 10px;
  font-size: 14px;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 10px;
}

.info-item {
  background-color: white;
  padding: 8px 12px;
  border-radius: 4px;
  font-size: 12px;
}

.button-group {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.test-btn, .clear-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.test-btn {
  background-color: #007bff;
  color: white;
}

.test-btn:hover:not(:disabled) {
  background-color: #0056b3;
}

.test-btn:disabled {
  background-color: #6c757d;
  cursor: not-allowed;
}

.clear-btn {
  background-color: #6c757d;
  color: white;
}

.clear-btn:hover {
  background-color: #545b62;
}

.logs-container {
  max-height: 300px;
  overflow-y: auto;
  background-color: #212529;
  border-radius: 4px;
  padding: 10px;
}

.no-logs {
  color: #6c757d;
  text-align: center;
  padding: 20px;
  font-style: italic;
}

.log-item {
  margin-bottom: 8px;
  padding: 6px;
  border-radius: 3px;
  font-size: 11px;
  line-height: 1.4;
}

.log-item.info {
  background-color: rgba(0, 123, 255, 0.1);
  color: #007bff;
}

.log-item.success {
  background-color: rgba(40, 167, 69, 0.1);
  color: #28a745;
}

.log-item.warning {
  background-color: rgba(255, 193, 7, 0.1);
  color: #ffc107;
}

.log-item.error {
  background-color: rgba(220, 53, 69, 0.1);
  color: #dc3545;
}

.log-time {
  color: #6c757d;
  margin-right: 8px;
}

.log-type {
  font-weight: bold;
  margin-right: 8px;
}

.log-message {
  flex: 1;
}

.log-data {
  margin-top: 6px;
  padding: 8px;
  background-color: rgba(0, 0, 0, 0.2);
  border-radius: 3px;
  font-size: 10px;
  overflow-x: auto;
  white-space: pre-wrap;
  color: #e9ecef;
}

@media (max-width: 768px) {
  .debug-panel {
    padding: 15px;
  }
  
  .info-grid {
    grid-template-columns: 1fr;
  }
  
  .button-group {
    flex-direction: column;
  }
  
  .test-btn, .clear-btn {
    width: 100%;
  }
}
</style>